package com.kkm.service.Imp;

import com.kkm.dao.GoodsDao;
import com.kkm.dao.Imp.GoodsDaoImp;
import com.kkm.pojo.Goods;
import com.kkm.pojo.PageBean;
import com.kkm.pojo.SongList;
import com.kkm.service.GoodsService;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class GoodsServiceImp implements GoodsService {
    GoodsDao goodsDao=new GoodsDaoImp();
    @Override
    public PageBean<Goods> selectAll(String currentPage, int rows) {
        int currPage=Integer.parseInt(currentPage);
        if(currPage<=0){
            currPage=1;
        }
        PageBean<Goods> pageBean=new PageBean(); //实例化pagebean对象
        int count= goodsDao.checkGoodsCount();//查询记录数

        int totalPage=count%rows==0?count/rows :count/rows+1;
        if(currPage>=totalPage){
            currPage=totalPage;
            System.out.println(currPage+"OrderService");
        }

        int index=(currPage-1)*rows;
        List<Goods> goodsList=goodsDao.showGoods(index,rows);

        pageBean.setRows(rows);
        pageBean.setCurrentPage(currPage);
        pageBean.setTotalPage(totalPage);
        pageBean.setTotalCount(count);
        pageBean.setList(goodsList);

        return pageBean;
    }

    @Override
    public PageBean<Goods> checkGoods(Map<String, String[]> condition, String currentPage, int rows) {
        int orderCount=goodsDao.checkGoodsCount();
        int num=0;
        Set<String> keySet=condition.keySet();
        for(String key:keySet) {
            String value = condition.get(key)[0];//获取值
            if (!"".equals(value)) {
                num++;
            }
        }
        if(num>2){
            orderCount=goodsDao.checkGoodsNum(condition);
        }

        if(orderCount>=1){
            int currPage=Integer.parseInt(currentPage);
            PageBean<Goods> pageBean=new PageBean(); //实例化pagebean对象

            int totalPage=orderCount%rows==0?orderCount/rows :orderCount/rows+1;
            int index=(currPage-1)*rows;
            List<Goods> goodsList=goodsDao.checkGoods(condition,index,rows);

            pageBean.setRows(rows);
            pageBean.setCurrentPage(currPage);
            pageBean.setTotalPage(totalPage);
            pageBean.setTotalCount(orderCount);
            pageBean.setList(goodsList);
            return pageBean;
        }
        return null;
    }

    @Override
    public void deleteGoods(int gid) {
        goodsDao.deleteGoods(gid);
    }

    @Override
    public Goods goodsById(int gid) {
        return goodsDao.goodsById(gid);
    }

    @Override
    public void modifyGoods(double price,int number, int gid) {
            goodsDao.modifyGoods(price, number,gid);
    }

    @Override
    public void addGoods(String gname, double price, int number, String gtype) {
            goodsDao.addGoods(gname,price,number,gtype);
    }
}
